package com.lv.common.utils;

import static android.content.Context.ACTIVITY_SERVICE;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lv.common.ktx.ViewKt;
import com.lv.common.network.support.YgxUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 常用的一些方法工具类
 */
public class MyUtils {

    public static Context mContext;

    public static void init(Context context) {
        mContext = context;
    }

    /**
     * 初始化工具类
     *
     * @param context 上下文
     */
//    public static void init(Context context) {
//        Utils.context = context.getApplicationContext();
//    }

    /**
     * 获取ApplicationContext
     *
     * @return ApplicationContext
     */
    public static Context getContext() {
        if (mContext != null) return mContext;
        throw new NullPointerException("u should init first");
    }

    /**
     * des加密相关
     */
    private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";//DES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    public static String ivparameterspec; //// 密钥也是这个  初始化向量参数，AES 为16bytes. DES 为8bytes.
    private static final String ALGORITHM = "DES";//DES是加密方式 ,处理密钥时用到

    //把String转化为double
    public static double convertToDouble(String number, double defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Double.parseDouble(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }

    /**
     * 隐藏软键盘
     *
     * @param v
     */
    public static void hideSoftInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    public static void showSoftInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (!imm.isActive()) {
            imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 把时间戳变为时间
     *
     * @param time
     */
    public static String getDateYMD(long time) {
        Date date = new Date(time);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String d = format.format(date);
        return d;
    }

    /*
     * 中文转unicode编码
     */
    public static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    //Unicode转中文
   /* public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }*/

    public static String decode2(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuffer retBuf = new StringBuffer();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else
                    retBuf.append(unicodeStr.charAt(i));
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }


    /**
     * 生成随机字符串
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(base.length());
            buf.append(base.charAt(index));
        }
        return buf.toString();
    }


    /**
     * 获取随机数字
     */
    public static String getRandomInt(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(base.length());
            builder.append(base.charAt(index));
        }
        return builder.toString();
    }


    /**
     * 判断当前点击屏幕的地方是否是软键盘：
     *
     * @param v
     * @param event
     * @return
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /**
     * byte/kb/mb/GB换算
     *
     * @return
     */
    public static String getSize(int number) {
        String parseSize = null;
        DecimalFormat df = new DecimalFormat("0.00");
        if (number < 1024) {
            parseSize = number + "B";
        } else if (number < 1024 * 1024) {
            parseSize = df.format(number / 1024f) + "K";
        } else if (number < 1024 * 1024 * 1024) {
            parseSize = df.format(number / 1024 / 1024f) + "M";
        } else {
            parseSize = df.format(number / 1024 / 1024 / 1024f + "G");
        }

        return parseSize;
    }


    /**
     * 格式化钱
     * 分
     *
     * @param value
     * @return
     */
    public static String formatMoneyBranch(String value) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(Double.parseDouble(value));
    }

    /**
     * 格式化钱
     * 分转化成元
     *
     * @param value
     * @return
     */
    public static String formatMoneyElement(String value) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(Double.parseDouble(value) / ((double) 100));
    }

    /**
     * 格式化钱
     * 亿
     *
     * @param value
     * @return
     */
    public static String formatMoneyYDot(String value) {

        double money = Double.parseDouble(value);

        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        String format = df.format(money);

        if (money >= 100000000) {
            format = df.format(money / 100000000) + "亿";
        } else if (money <= -100000000) {
            format = df.format(money / 100000000) + "亿";
        } else {
            format = df.format(money);

        }
        if (format.contains(".00")) {
            format = format.replace(".00", "");
        }
        return format;
    }

    /**
     * 格式化钱
     * 分转化成万
     *
     * @param value
     * @return
     */
    public static String formatMoneyWanTwoDot(String value) {
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        double money = Double.parseDouble(value);
        String format = "0";
//        format = df.format(money);

        if (money >= 100000000) {
            format = df.format(money / 100000000) + "亿";
        } else if (money >= 10000) {
            format = df.format(money / 10000) + "万";
        } else if (money <= -100000000) {
            format = df.format(money / 100000000) + "亿";
        } else if (money <= -10000) {
            format = df.format(money / 10000) + "万";
        } else {
            format = df.format(money);

        }
        if (format.contains(".00")) {
            format = format.replace(".00", "");
        }
        return format;
    }

    /**
     * 格式化钱
     *
     * @param value
     * @return 小于万两位小数，大于万，最小有效小数位
     */
    public static String formatMoneyFormatWan(String value) {

        double money = Double.parseDouble(value);

        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        String format = "0";
        format = df.format(money);
        if (money >= 100000000) {
            format = df.format(money / 100000000);
            format = ViewKt.priceSmallDot(format, "") + "亿";
        } else if (money >= 10000) {
            format = df.format(money / 10000);
            format = ViewKt.priceSmallDot(format, "") + "万";
        } else if (money <= -100000000) {
            format = df.format(money / 100000000);
            format = ViewKt.priceSmallDot(format, "") + "亿";
        } else if (money <= -10000) {
            format = df.format(money / 10000);
            format = ViewKt.priceSmallDot(format, "") + "万";
        } else {
            format = df.format(money);
        }

        return format;
    }


    /**
     * @param string 接收需要加密的信息
     * @return 返回经过md5加密后的值
     */
    public static String DoMd5(String string) {
        //如果传入是空值，返回空值
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            //此处正常返回加密后的值
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //如果异常那么直接返回""
        return "";
    }

    /**
     * 32位MD5加密的大写字符串
     *
     * @param s
     * @return
     */
    public final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密 方法的重载
     *
     * @param string 需要加密信息
     * @param times  加密次数
     * @return 返回加密后的内容
     */
    public static String DoMd5(String string, int times) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        //重载
        String md5 = DoMd5(string);
        //多次加密
        for (int i = 0; i < times - 1; i++) {
            md5 = DoMd5(md5);
        }
        return md5;
    }

    /**
     * 把时间转化为时间戳(13位)
     *
     * @param date 时间格式应该为:1900/10/10 12:24:26
     * @return
     */
    public static long getTime(String date) {
        long time = 0;
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        try {
            Date parse = format.parse(date);
            time = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 把时间转化为时间戳(13位)
     *
     * @param date 时间格式应该为:1900/10/10
     * @return
     */
    public static long getTimeYMDs(String date) {
        long time = 0;
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Date parse = format.parse(date);
            time = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 把时间戳变为时间
     *
     * @param time
     */
    public static String getDate(String time) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String d = format.format(time);
        return d;
    }


    /**
     * 设置TextView分段显示颜色 </br>
     * <p>
     * 用法:</br> SpannableStringBuilder style =Tools.setTextDifferent(context,new
     * String[] { replayModle.getName(),"回复", replayModle.getReturnUserName(),
     * ": " + replayModle.getContent() },
     * <p>
     * new int[] { R.color.find_name, R.color.dark, R.color.find_name,
     * R.color.dark });
     * <p>
     * tv.setText(style);
     *
     * @param context
     * @param strs    字符串数组
     * @param colors  字符串对应颜色Id数组
     * @return SpannableStringBuilder
     */
    public static SpannableStringBuilder setTextDifferent(Context context,
                                                          String[] strs, int[] colors) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : strs) {
            if (str != null) {
                stringBuffer.append(str);
            }
        }
        SpannableStringBuilder style = new SpannableStringBuilder(new String(
                stringBuffer));
        int len = strs.length;
        int startIndex = 0;
        int endIndex = 0;
        for (int i = 0; i < len; i++) {
            endIndex += strs[i].length();
            style.setSpan(new ForegroundColorSpan(context.getResources()
                            .getColor(colors[i])), startIndex, endIndex,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            startIndex = endIndex;

        }
        return style;
    }

    /**
     * dip转换px
     */
    public static int dip2px(int dip, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }


    /**
     * 验证手否是手机号?
     *
     * @param phoneNum 手机号码
     * @return
     */
    public static boolean isPhoneNumber(String phoneNum) {
        // 验证手机的正则表达式
//		String str = "^[1]([3][0-9]{1}|59|58|88|89|77)[0-9]{8}$";
        String str = "[1][0-9]{10}$";
        Pattern pattern = Pattern.compile(str);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.matches();
    }


    /**
     * 判断是否联网的方法
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * base64编码字符集转化成图片文件。
     *
     * @param base64Str
     * @param path      文件存储路径
     * @return 是否成功
     */
    public static boolean base64ToFile(String base64Str, String path) {
        byte[] data = Base64.decode(base64Str, Base64.DEFAULT);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 版本号比较
     *
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
//        Log.d("HomePageActivity", "version1Array=="+version1Array.length);
//        Log.d("HomePageActivity", "version2Array=="+version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
//        Log.d("HomePageActivity", "verTag2=2222="+version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    public static boolean isExistActivity(Context mContext, Class<?> activity) {
        Intent intent = new Intent(mContext, activity);
        ComponentName cmpName = intent.resolveActivity(mContext.getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);//
            //这里获取的是APP栈的数量，一般也就两个
            ActivityManager.RunningTaskInfo runningTaskInfo = taskInfoList.get(0);// 只是拿          当前运行的栈
            int numActivities = taskInfoList.get(0).numActivities;

            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) {// 说明它已经启动了
                    flag = true;
                    break;//跳出循环，优化效率
                }
            }
        }
        return flag;

    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    /**
     * 图片显示设置
     *
     * @param url
     * @param with
     * @param height
     * @param q
     * @return
     */
    public static String makeSmallerImg(String url, int with, int height, int q) {
        //http://suyiyong.oss-cn-hangzhou.aliyuncs.com/1025pt.jpg?x-oss-process=image/resize,limit_0,m_fill,w_500,h_500/quality,q_50
        url = url + "?x-oss-process=image/resize,limit_0,m_fill,w_" + with + ",h_" + height + "/quality,q_" + q;
        return url;
    }

    /**
     * 图片显示设置
     *
     * @param url
     * @param with
     * @param q
     * @return
     */
    public static String makeSmallerImg(String url, int with, int q) {
        //http://suyiyong.oss-cn-hangzhou.aliyuncs.com/1025pt.jpg?x-oss-process=image/resize,limit_0,m_fill,w_500,h_500/quality,q_50
        url = url + "?x-oss-process=image/resize,limit_0,m_fill,w_" + with + "/quality,q_" + q;
        return url;
    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    // 目标SD路径：/storage/emulated/0
    public static String getSDPath(Context context) {
        String sdPath = "";
        boolean isSDExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //判断SD卡是否存在
        if (isSDExist) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                File externalFileRootDir = context.getExternalFilesDir("");
                sdPath = context.getExternalFilesDir(null).getAbsolutePath();
//                do {
//                    externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
//                } while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));
//                sdPath = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
            } else {
                sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            }
        } else {
            sdPath = Environment.getRootDirectory().toString();//获取跟目录
        }
        return sdPath;
    }

    // 将字符串写入到文本文件中
    public static File writeTxtToFile(String strcontent, String filePath, String fileName) {
        filePath = getSDPath(mContext) + filePath;
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
//        String strFilePath =  fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {

                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
//            file = new File(filePath + fileName);
            file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 判断集合是否是null或者空
     */
    public static boolean isNullOrEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    public static <T> void setRefreshLayoutState(SmartRefreshLayout mRefreshLayout, List<T> items, boolean ishas) {
        if (mRefreshLayout == null) {
            return;
        }
        mRefreshLayout.finishLoadMore();
        if (items == null) {
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.finishLoadMoreWithNoMoreData();
        } else if (items.size() == 0) {
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.finishLoadMoreWithNoMoreData();
        } else if (ishas) {
            mRefreshLayout.finishLoadMoreWithNoMoreData();
            mRefreshLayout.setEnableLoadMore(true);
        } else {
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.finishLoadMore(true);
        }
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
    }


    /**
     * 自动刷新的view 设置数据
     *
     * @param page
     * @param pageSize
     * @param mRefreshLayout
     * @param beans
     * @param items
     * @param mAdapter
     * @param <T>
     * @param <V>
     */
    public static <T, V extends BaseQuickAdapter> void recyclerviewSetData(int page, int pageSize
            , SmartRefreshLayout mRefreshLayout, List<T> beans, List<T> items, V mAdapter) {
        if (page == 1) {
            beans.clear();
        }
        if (!isNullOrEmpty(items)) {
            beans.addAll(items);
            boolean ishas = true;
            if (items.size() < pageSize) {
                ishas = false;
            }
            MyUtils.setRefreshLayoutState(mRefreshLayout, items, ishas);
        }
        mAdapter.notifyDataSetChanged();
        if (isNullOrEmpty(items)) {
            MyUtils.setRefreshLayoutState(mRefreshLayout, items, false);
        }
    }

    private static byte[] getPicture(Drawable drawable) {
        if (drawable == null) {
            return null;
        }
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bitmap = bd.getBitmap();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        return os.toByteArray();
    }

    public static void onClearMemory(Context context) {

        ActivityManager activityManger = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = activityManger.getRunningAppProcesses();
        if (list != null)
            for (int i = 0; i < list.size(); i++) {
                ActivityManager.RunningAppProcessInfo apinfo = list.get(i);
                String[] pkgList = apinfo.pkgList;
                if (apinfo.importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (int j = 0; j < pkgList.length; j++) {
                        if (pkgList[j].equals(context.getPackageName())) {
                            continue;
                        }
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
                            activityManger.restartPackage(pkgList[j]);
                        } else {
                            activityManger.killBackgroundProcesses(pkgList[j]);
                        }
                    }
                }
            }
    }

    //保存文本内容到剪切板
    public static void copyClicks(String text) {
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);

        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
        ClipData clipData = ClipData.newPlainText(null, text);

        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData);
    }

    //从剪切板粘贴文本
    public static String pasteClicks() {
        String text = "";
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        // 获取剪贴板的剪贴数据集
        ClipData clipData = clipboard.getPrimaryClip();

        if (clipData != null && clipData.getItemCount() > 0) {
            // 从数据集中获取（粘贴）第一条文本数据
            text = clipData.getItemAt(0).getText().toString();
        }
        return text;
    }


    /**
     * 检测程序是否安装
     *
     * @param packageName
     * @return
     */
    public static boolean isInstalled(String packageName) {
        PackageManager manager = mContext.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        if (installedPackages != null) {
            for (PackageInfo info : installedPackages) {
                if (info.packageName.equals(packageName))
                    return true;
            }
        }
        return false;
    }

}
